package models.user;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import play.Logger;
import play.db.ebean.Model;
import utils.MengException;

/**
 * 用户头像
 * @author zhangpeng
 *
 */

@Entity
@Table(name="portrait_user_info")
public class PortraitUserInfo extends Model{

	private static final long serialVersionUID = 1L;
	
	@Id
	public long id;
	public String username;
	/**
	 * 头像url，上传云存储
	 */
	public String portrait;
	
	public static PortraitUserInfo getInstances(){
		return new PortraitUserInfo();
	}
	
	public static Model.Finder<Long, PortraitUserInfo> find = new Model.Finder<Long, PortraitUserInfo>(Long.class, PortraitUserInfo.class);
	
	/**
	 * 创建用户头像
	 * 
	 * @param pui
	 * @return
	 * @throws MengException
	 */
	public boolean createPUI(PortraitUserInfo pui) throws MengException {

		if (UserInfo.getInstances().verifyUsername(pui.username)) {
			throw new MengException("600001", "用户名不存在");
		}

		if (verifyPortraitUserInfo(pui.username)) {
			throw new MengException("600002", "用户头像已存在");
		}

		try {
			pui.save();
			return true;
		} catch (Throwable t) {
			t.printStackTrace();
			Logger.error("UserInfo createPUI Exception," + t.getMessage());
			throw new MengException("600003", "用户头像保存失败");
		}
	}

	public boolean createPUI(UserInfo ui) throws MengException {

		if (verifyPortraitUserInfo(ui.username)) {
			throw new MengException("600008", "用户基本信息已存在");
		}
		PortraitUserInfo pui = getInstances();
		pui.username = ui.username;
		try {
			pui.save();
			return true;
		} catch (Throwable t) {
			t.printStackTrace();
			Logger.error("UserInfo createBUI Exception," + t.getMessage());
			throw new MengException("600009", "用户基本信息保存失败");
		}
	}

	/**
	 * 用户头像修改
	 * 
	 * @param pui
	 * @return
	 * @throws MengException
	 */
	public boolean modifyPUI(PortraitUserInfo pui) throws MengException {

		if (UserInfo.getInstances().verifyUsername(pui.username)) {
			throw new MengException("600004", "用户名不存在");
		}
		pui.id = getPUI(pui.username).id;

		try {
			pui.update();
			return true;
		} catch (Throwable t) {
			t.printStackTrace();
			Logger.error("UserInfo modifyPUI Exception," + t.getMessage());
			throw new MengException("600005", "用户头像修改失败");
		}
	}

	/**
	 * 获取用户头像
	 * 
	 * @param username
	 * @return
	 * @throws MengException
	 */
	public PortraitUserInfo getPUI(String username) throws MengException {

		if (UserInfo.getInstances().verifyUsername(username)) {
			throw new MengException("600006", "用户名不存在");
		}

		try {

			return find.where().eq("username", username).findUnique();
		} catch (Throwable t) {
			t.printStackTrace();
			Logger.error("UserInfo getPUI Exception," + t.getMessage());
			throw new MengException("600007", "获取用户头像失败");
		}
	}
	
	public boolean verifyPortraitUserInfo(String username) throws MengException {

		if (getPUI(username) != null) {
			return true;
		}

		return false;
	}

}
